import serial
import time
import os
import sys
import random
import re

# 定义常量
UART_PORT = ""
DEBUG_PORT = "COM4"
AT_PORT = "COM42"
MODEM_PORT = ""
BAUDRATE = 115200

# 定义变量
uart_serial = None
debug_serial = None
at_serial = None
modem_serial = None

# 记录运行次数
runTimes = 1
# 记录运行失败次数
runFailTimes = 0

# 是否需要登录
needCheckLockStat = 1

# log文件
AT_LOG = ""
DEBUG_LOG = ""
STATISTIC_LOG = ""


# log写入函数
def write_log(log, logFile=""):
    with open(logFile, "a") as file_object:
        file_object.write(
            str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            + "\r\n"
            + log
            + "\r\n"
        )
        print(log)


# 发送at指令
def at_write(command, timeout, at_port_opened, at_result, RDY=0, CPIN=0):
    at_command = command.encode("UTF-8")
    at_port_opened.write(at_command)


# 读取at口返回
def at_read(at_port_opened):
    rec_str = ""
    while True:
        time.sleep(1)
        lenth = at_port_opened.inWaiting()
        if lenth > 0:
            rec_str = at_port_opened.read(size=lenth)
            try:
                return re.sub("\\x1b.*?m", "", rec_str.decode("UTF-8"), 0, re.I)
            except:
                return ""
        else:
            break
    return rec_str


# 检查端口连接状态
def check_port_status():
    global uart_serial
    global debug_serial

    try:
        debug_serial = serial.Serial(DEBUG_PORT, BAUDRATE)
    except:
        print("debug口连接失败，请检查端口")
        sys.exit()


# 检查AT口通信状态
def check_AT_singnal():
    global at_serial

    if at_serial == None:
        try:
            at_serial = serial.Serial(AT_PORT, BAUDRATE)
        except:
            print("at口连接失败，请检查端口")
            sys.exit()


def loginDevice():

    # 确认登录失败的条件，或者，不可能失败
    while True:
        print("等待登录... ... ")
        time.sleep(3)
        at_write("\r\n", 3, debug_serial, "OK")
        result = at_read(debug_serial)
        print(result)

        with open(DEBUG_LOG, "a") as file_object:
            file_object.write(result)

        if "login:" in result:
            at_write("root\r\n", 3, debug_serial, "OK")
            print("账号输入成功")
            time.sleep(2)
            at_write("oelinux123\r\n", 3, debug_serial, "OK")
            print("密码输入成功")
        elif ("~ #" in result) or ("/ #" in result):
            print("登录成功")
            break
        else:

            continue


def creatLogFile():
    global AT_LOG
    global DEBUG_LOG
    global STATISTIC_LOG
    AT_LOG = "AT_LOG_{}.log".format(
        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
    )
    DEBUG_LOG = "DEBUG_LOG_{}.log".format(
        time.strftime("%Y-%m-%d_%H_%M_%S", time.localtime())
    )


def writeRuntimesToLog():
    global runTimes
    global runFailTimes
    with open(DEBUG_LOG, "a+") as file_object:
        file_object.write(
            "\r\n{} runtimes: {} FAIL: {} {}\r\n".format(
                "<" * 20, runTimes, runFailTimes, ">" * 20
            )
        )
    with open(AT_LOG, "a+") as file_object:
        file_object.write(
            "\r\n{} runtimes: {} FAIL: {} {}\r\n".format(
                "<" * 20, runTimes, runFailTimes, ">" * 20
            )
        )

    runTimes += 1


def get_logcat():
    # SYNC receipt timeout
    at_write("logcat > /tmp/logcat.txt\r\n", 3, debug_serial, "OK")
    time.sleep(2)
    at_write("logcat -b events > tmp/events.txt\r\n", 3, debug_serial, "OK")
    time.sleep(2)


def check_logcat():
    os.popen("adb pull /data/logcattest.txt  E:\ ")
    time.sleep(10)
    write_log("检查debug口的log输出", DEBUG_LOG)
    result = at_read(debug_serial)
    with open(DEBUG_LOG, "a+") as file_object:
        file_object.write(result)

    with open("E:\logcattest.txt", "r", encoding="utf-8") as fp1:
        value = fp1.readlines()
        if (
            "update nitz time info failed, cri_nas_nw_network_time_info global variable is null"
            in value[-1]
        ):
            write_log("有update nitz time info failed", DEBUG_LOG)
            at_write("ps |grep mcm\r\n", 3, debug_serial, "OK")
            result = at_read(debug_serial)
            if "mcm_ril_service" in result:
                print("问题复现并修复成功")
                input("暂停")
            else:
                write_log("1继续复现", DEBUG_LOG)
        else:
            write_log("2继续复现", DEBUG_LOG)
    time.sleep(1)
    os.remove("E:\logcattest.txt")


def mainfunc():
    global runTimes
    global runFailTimes
    tag = 0

    at_write("logcat > /tmp/logcat.txt &\r\n", 3, debug_serial, "OK")
    time.sleep(2)
    at_write("logcat -b events > /tmp/events.txt &\r\n", 3, debug_serial, "OK")
    time.sleep(2)
    result = at_read(debug_serial)
    with open(DEBUG_LOG, "a+") as file_object:
        file_object.write("步骤一： {}\r\n".format(result))

    at_write("AT+QMSSR=3\r\n", 3, at_serial, "OK")
    result = at_read(at_serial)
    with open(AT_LOG, "a+") as file_object:
        file_object.write("步骤二： {}\r\n".format(result))

    at_write("cd /data\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    at_write("./test_sdk_api\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    # 运行test_sdk_api
    at_write("2\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    at_write("0\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    at_read(debug_serial)
    # 固定5G：ql_nw_set_pref_nwmode_roaming
    at_write("4\n40\n1\n", 3, debug_serial, "OK")
    time.sleep(1)
    result = at_read(debug_serial)
    with open(DEBUG_LOG, "a+") as file_object:
        file_object.write("步骤三 固定5G： {}\r\n".format(result))

    if "ql_nw_set_config ret = 0" in result:
        print("固定5G成功\r\n")
    else:
        print("固定5G失败!!!\r\n")
        tag = 1

    for i in range(30):
        if i == 29:
            print("1分钟内信号强度未发生变化\r\n")
            tag = 1

        at_write("10\r\n", 3, debug_serial, "OK")
        result = at_read(debug_serial)
        singal_5G_result = re.findall(
            "nr5g_sig_info: rsrp=-\d+, rsrq=-\d+, snr=\d+", result
        )[0]
        time.sleep(1)
        at_write("10\r\n", 3, debug_serial, "OK")
        result = at_read(debug_serial)
        singal_5G_result_sec = re.findall(
            "nr5g_sig_info: rsrp=-\d+, rsrq=-\d+, snr=\d+", result
        )[0]
        time.sleep(1)
        if singal_5G_result != singal_5G_result_sec:
            print("信号强度发生变化 ，pass\r\n")
            with open(DEBUG_LOG, "a+") as file_object:
                file_object.write(
                    "步骤三 读取信号强度： \r\n{}\r\n{}\r\n".format(
                        singal_5G_result, singal_5G_result_sec
                    )
                )
            break
        elif "strength level is UNKNOWN" in singal_5G_result:
            print("信号丢失！！！\r\n")
            tag = 1
        else:
            with open(DEBUG_LOG, "a+") as file_object:
                file_object.write(
                    "步骤三 读取信号强度： \r\n{}\r\n{}\r\n".format(
                        singal_5G_result, singal_5G_result_sec
                    )
                )

    at_write("-1\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    # 进入dm
    at_write("7\r\n", 3, debug_serial, "OK")
    time.sleep(2)
    at_write("0\r\n", 3, debug_serial, "OK")
    time.sleep(2)
    at_read(debug_serial)
    # 调用ql_dm_set_modem_restart接口重启modem
    at_write("29\r\n", 3, debug_serial, "OK")
    time.sleep(3)
    result = at_read(debug_serial)
    # print("重启modem接口调用结果：", result)
    if "set modem restart, ret = 0" in result:
        print("接口重启modem成功\r\n")
    else:
        print("接口重启modem失败!!!\r\n")
        tag = 1

    at_write("-1\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    at_write("-1\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    at_write("ps| grep ril\r\n", 3, debug_serial, "OK")
    time.sleep(1)
    result = at_read(debug_serial)
    if "/usr/bin/mcm_ril_service" in result:
        print("接口重启modem后 mcm_ril_service进程存在\r\n")
        with open(DEBUG_LOG, "a+") as file_object:
            file_object.write(
                "步骤三 接口重启modem后检查mcm_ril_service进程是否存在： {}\r\n".format(
                    result
                )
            )
    else:
        print("接口重启modem后 mcm_ril_service进程不存在!!!\r\n")
        with open(DEBUG_LOG, "a+") as file_object:
            file_object.write(
                "步骤三 接口重启modem后检查mcm_ril_service进程是否存在： {}\r\n".format(
                    result
                )
            )
        sys.exit()

    if tag:
        runFailTimes += 1


if __name__ == "__main__":

    # 连接端口
    check_port_status()
    creatLogFile()
    loginDevice()
    time.sleep(5)

while True:
    writeRuntimesToLog()
    time.sleep(10)
    check_AT_singnal()
    # 检查AT是否正常

    mainfunc()
